package com.skywolf.chem.manager.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.skywolf.chem.article.entity.Article;
import com.skywolf.chem.article.entity.Position;
import com.skywolf.chem.article.pojo.ArticleApproveParam;
import com.skywolf.chem.article.pojo.ArticleQueryParam;
import com.skywolf.chem.article.service.IArticleService;
import com.skywolf.chem.common.sysconfig.pojo.vo.PageVO;
import com.skywolf.chem.common.sysconfig.response.RespData;
import com.skywolf.chem.pageconfig.entity.FirstPage;
import com.skywolf.chem.pageconfig.service.IFirstPageService;
import com.skywolf.chem.usercenter.entity.User;
import com.skywolf.chem.usercenterapi.entity.CustomerInfo;
import com.skywolf.chem.usercenterapi.service.IPositionService;
import com.skywolf.chem.common.context.LoginUser;
import com.skywolf.chem.common.context.RequestContext;
import com.skywolf.chem.common.enums.ResponseCodeEnum;
import com.skywolf.chem.pageconfig.entity.ColumnInfo;
import com.skywolf.chem.pageconfig.service.IColumnInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 * 帖子 前端控制器
 * </p>
 *
 * @author 
 * @since 2020-06-09
 */
@Slf4j
@RestController
@RequestMapping("/manager/article")
@Api(value = "管理端-新闻相关", description = "管理端-新闻相关")
public class ArticleManagerController {

    @Autowired
    IArticleService articleService;

    @Autowired
    IColumnInfoService columnInfoService;

    @Autowired
    IPositionService positionService;

    @Autowired
    IFirstPageService firstPageService;

    @ApiOperation(value = "帖子列表",notes = "帖子列表")
    @RequestMapping(value = "/getArticles",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<Article> getArticles(@RequestBody @Validated ArticleQueryParam queryParam) {
        LoginUser user = RequestContext.getLoginUser();
        PageVO<Article> page = articleService.pageArticleListManager(queryParam,user.getCity());
        return RespData.success(page);
    }

    @ApiOperation(value = "根据栏目id，查询栏目下帖子",notes = "根据栏目，查询栏目下帖子")
    @RequestMapping(value = "/getArticleByCol",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<Article> getArticleByCol(@RequestBody @Validated ArticleQueryParam queryParam) {
        PageVO<Article> page = articleService.pageArticleList(queryParam);
        return RespData.success(page);
    }

    @ApiOperation(value = "根据帖子id，查询帖子详情",notes = "根据帖子id，查询帖子详情")
    @RequestMapping(value = "/getArticleDetail",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<Article> getArticleDetail(@RequestParam(value = "id",required = true) Long id) {
        Article article = articleService.getById(id);
        article.setCreatedTime(article.getAddTime());
        article.setPcCover(0);
        ColumnInfo columnInfo = positionService.getColByAticleId(id);
        if(columnInfo!=null){
            article.setColId(columnInfo.getId());
            article.setColName(columnInfo.getColName());
            article.setTopping(columnInfo.getTopping());
            article.setPcCover(columnInfo.getPcCover());
        }
        QueryWrapper<FirstPage> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FirstPage::getArticleId, id);
        FirstPage firstPage = firstPageService.getOne(queryWrapper);
        if(firstPage!=null){
            article.setPcfirst(firstPage.getContentType());
        }else{
            article.setPcfirst(-1);
        }
        return RespData.success(article);
    }

    @ApiOperation(value = "创建帖子",notes = "创建帖子")
    @RequestMapping(value = "/addArticle",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<Article> addArticle(@RequestBody @Validated Article article) {
        if(article.getColId()==null){
            return RespData.error("请选择新闻栏目！");
        }
        article.setCreatedTime(LocalDateTime.now());
        article.setAddTime(LocalDateTime.now());
        articleService.save(article);
        if(article.getColId()!=null){
            ColumnInfo columnInfo = columnInfoService.getById(article.getColId());
            if(columnInfo==null){
                return RespData.failure(ResponseCodeEnum.COLUMNS_NO_ERROR);
            }
            Position position = new Position();
            position.setColumnId(article.getColId());
            position.setArticleId(article.getId());
            position.setArticleType(0);
            position.setTopping(article.getTopping());
            if(article.getPcCover()!=null && article.getPcCover()==1){
                position.setPcCover(1);
            }
            positionService.save(position);
        }
        if(article.getPcfirst()!=null && article.getPcfirst()!=-1){
            FirstPage firstPage = new FirstPage();
            firstPage.setArticleId(article.getId());
            firstPage.setContentType(article.getPcfirst());
            firstPageService.save(firstPage);
        }
        return RespData.success("success");
    }


    @ApiOperation(value = "更新帖子信息",notes = "更新帖子信息")
    @RequestMapping(value = "/updateArticle",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<Article> updateArticle(@RequestBody @Validated Article article) {
        article.setCreatedTime(null);
        article.setAddTime(null);
        article.setUpdatedTime(LocalDateTime.now());
        articleService.updateById(article);
//        article.setUpdatedTime(LocalDateTime.now());
//        articleService.updateArticle(article);
        if(article.getColId()!=null){
            ColumnInfo columnInfo = columnInfoService.getById(article.getColId());
            if(columnInfo==null){
                return RespData.failure(ResponseCodeEnum.COLUMNS_NO_ERROR);
            }
            QueryWrapper<Position> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Position::getArticleId, article.getId());
            Position positionOld = positionService.getOne(queryWrapper);
            if(positionOld==null){
                positionOld = new Position();
                positionOld.setArticleId(article.getId());
                positionOld.setColumnId(article.getColId());
                positionOld.setArticleType(0);
                positionOld.setTopping(article.getTopping());
                if(article.getPcCover()!=null && article.getPcCover()==1){
                    positionOld.setTopping(3);
                }
                positionService.save(positionOld);
            }else{
                Position position = new Position();
                position.setTopping(article.getTopping());
                position.setColumnId(article.getColId());
                if(article.getPcCover()!=null){
                    position.setPcCover(article.getPcCover());
                }
                positionService.update(position,
                        new UpdateWrapper<Position>().eq("article_id", article.getId()));
            }
        }
        if(article.getPcfirst()!=null){
            if(article.getPcfirst()==-1){
                firstPageService.delPCFirstPageData(article.getId());
            }else{
                QueryWrapper<FirstPage> firstWrapper = new QueryWrapper<>();
                firstWrapper.eq("article_id", article.getId());
                firstWrapper.eq("content_type", article.getPcfirst());
                FirstPage firstPage = firstPageService.getOne(firstWrapper);
                if(firstPage==null){
                    firstPage = new FirstPage();
                    firstPage.setArticleId(article.getId());
                    firstPage.setHot(article.getTopping());
                    firstPage.setContentType(article.getPcfirst());
                    firstPageService.save(firstPage);
                }else{
                    firstPage.setContentType(article.getPcfirst());
                    firstPage.setHot(article.getTopping());
                    firstPageService.updateById(firstPage);
                }
            }
        }
        return RespData.success("success");
    }


    @ApiOperation(value = "删除帖子",notes = "删除帖子")
    @RequestMapping(value = "/delArticleById",method = {RequestMethod.GET},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<Article> delArticleById(@RequestParam(value = "id",required = true) Long id) {
        articleService.removeById(id);
        positionService.deletePosition(id);
        firstPageService.delPCFirstPageData(id);
        return RespData.success("success");
    }

    @ApiOperation(value = "审核帖子",notes = "审核帖子")
    @RequestMapping(value = "/approvalArticle",method = {RequestMethod.POST},produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespData<String> approvalArticle(@RequestBody @Validated ArticleApproveParam articleApproveParam) {
        Article info = new Article();
        info.setId(articleApproveParam.getId());
        info.setArtStatus(articleApproveParam.getStatus());
        if(StringUtils.isNotBlank(articleApproveParam.getApproveStr())){
            info.setStatusDesc(articleApproveParam.getApproveStr());
        }
        LoginUser user = RequestContext.getLoginUser();
        if(user!=null){
            info.setAppoveUserId(user.getId());
        }
        info.setCreatedTime(null);
        info.setAddTime(null);
        info.setUpdatedTime(LocalDateTime.now());
        articleService.updateById(info);
        return RespData.success("success");
    }

    @ApiOperation(value = "修改封面图")
    @ResponseBody
    @RequestMapping(value = "/delCover", method = RequestMethod.GET)
    private RespData<String> delCover(@RequestParam(value = "articleId") Long articleId,
                                      @RequestParam(value = "index") Integer index,
                                      HttpServletRequest request) {
        try {
            Article article = articleService.getById(articleId);
            String img = article.getCoverUrl();
            if(StringUtils.isNotBlank(img)){
                String[] list = img.split(",");
                if(list.length-1>=index){
                    String exchangeStr = list[index];
                    img = img.replaceAll(exchangeStr,"");
                    img = img.replaceAll(",,",",");
                    if(StringUtils.isNotBlank(img)){
                        if(img.startsWith(",")){
                            img = img.substring(1,img.length());
                        }
                        if(img.endsWith(",")){
                            img = img.substring(0,img.length()-1);
                        }
                    }
                    if(img.length()<=1){
                        img = "";
                    }
                    article.setCoverUrl(img);
                    article.setCreatedTime(null);
                    article.setAddTime(null);
                    article.setUpdatedTime(LocalDateTime.now());
                    articleService.updateById(article);
                }
            }
        } catch (Exception e) {
            log.error("FileController.upload error:{}", e);
        }
        return RespData.success("cuccess");
    }

}
